﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Linq.Expressions;
using System.Web;
using System.Web.Services;
using RPGX.Data;

namespace RPGX.AuthenticationServer
{
    /// <summary>
    /// Summary description for Authentication
    /// </summary>
    [WebService(Namespace = "http://tempuri.org/")]
    [WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
    [System.ComponentModel.ToolboxItem(false)]
    // To allow this Web Service to be called from script, using ASP.NET AJAX, uncomment the following line. 
    // [System.Web.Script.Services.ScriptService]
    public class Authentication : System.Web.Services.WebService
    {
        [WebMethod]
        public AuthenticationResult Authenticate(string username, string password)
        {
            AuthenticationResult res = new AuthenticationResult();

            try
            {
                RPGXAuthenticationEntities context = new RPGXAuthenticationEntities();

                var account = (from a in context.ClientAccounts
                               where a.UserName.ToLower().Trim() == username.ToLower().Trim() &&
                                  a.Password == password
                               select a).SingleOrDefault();

                res.CouldConnectToServer = true;

                if (account == null)
                {
                    res.Authenticated = false;
                }
                else
                {
                    res.ClientAccountId = account.ClientAccountId;

                    var server = (from s in context.Servers
                                  where s.ServerId == account.ServerId
                                  select s).SingleOrDefault();

                    if (server == null)
                        throw new NullReferenceException(String.Format("Failed to find server with id: {0}",
                            account.ServerId));

                    res.ServerAddress = server.Address;
                    res.ServerName = server.Name;
                    res.ServerPort = server.Port;

                    res.Authenticated = true;
                }
            }
            catch (Exception)
            {
                res.CouldConnectToServer = false;
            }

            return res;
        }
    }
}
